package com.film.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//生成验证码
/**
 * 该控制类用来做验证码的生成
 * @author 2119196781
 *
 */
@WebServlet("/verify.jpg")
public class VerifyCodeController extends HttpServlet {
    
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	String text = "" ;//存储验证码
        char[] codes = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM".toCharArray();
        Random r = new Random();
        Color[] colors = {
                Color.red,
                Color.pink,
                Color.blue,
                Color.green
        };
        //创建一张图片对象（内存） 宽度，高度
        BufferedImage image = new BufferedImage(140,30,BufferedImage.TYPE_INT_RGB);

        //获得一个画笔 (绘图工具)
        Graphics graphics = image.getGraphics();

        //画一个矩形的背景，设置颜色
        graphics.setColor(Color.YELLOW);
        graphics.fillRect(0,0,180,40);

        //加点干扰
        for(int i=0;i<=30;i++){
            graphics.setColor(colors[r.nextInt(colors.length)]);
            int x1 = r.nextInt(180);
            int x2 = r.nextInt(180);

            int y1 = r.nextInt(40);
            int y2 = r.nextInt(40);
            graphics.drawLine(x1,y1,x2,y2);
        }

        Font font = new Font("楷体",Font.BOLD,25);
        graphics.setFont(font);
        //在图片写验证码
        for(int i=0;i<4;i++){
            int index = r.nextInt(codes.length); // [0-10)
            char c = codes[index];
            text+=c;

            graphics.setColor(Color.BLACK);
            graphics.drawString(String.valueOf(c),10+35*i,25);
        }
        ImageIO.write(image,"jpg",resp.getOutputStream());//将图片写到浏览器

        req.getSession().setAttribute("code",text);
    }
}
